package com.demo.server1.service;

import com.demo.dto.UserModifyDTO;
import com.demo.rpc.annotation.RPCTransactional;
import com.demo.server1.dao.UserDao;
import com.demo.server1.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by hunter
 *
 * @Description
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RpcClient rpcClient;

    /**
     * 普通rpc测试
     */
    public String test() {
        return rpcClient.test();
    }

    /**
     * 分布式事务rpc测试
     *
     * @param name
     */
    @RPCTransactional
    public void testTransactional(String name) {

        // rpc 远程事务 更新用户2
        UserModifyDTO modifyDTO = new UserModifyDTO();
        modifyDTO.setUserId(2);
        modifyDTO.setName(name);
        System.out.println(rpcClient.testTransactional(modifyDTO));

        // 本地事务, 更新用户1
        modifyDTO.setUserId(1);
        this.updateUser(modifyDTO);

        // 模拟业务错误, 此时本地事务不会被提交, server2、server3的事务应该被回滚
        // throw new RuntimeException();

        // 模拟超时, 此时三个serer的事务都会被回滚, server2、server3事务超时
        /*try {
            Thread.sleep(15 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 一个简单的service方法
     *
     * @param modifyDTO
     */
    @Transactional
    public void updateUser(UserModifyDTO modifyDTO) {
        User user = new User();
        user.setId(modifyDTO.getUserId());
        user.setName(modifyDTO.getName());

        userDao.save(user);
    }
}